﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Morphine.Media
{
    public static class Playlist
    {
        public static void Save(string file, List<MediaInfo> mediaCollection)
        {
            var x = new XElement("Playlist", from entry in mediaCollection
                                                  orderby entry.Artist, entry.Album
                                                  select new XElement("Entry", new XAttribute("Artist", entry.Artist), new XAttribute("Album", entry.Album),
                                                      new XAttribute("Title", entry.Title), new XAttribute("File", entry.File)));

            x.Save(file);
        }

        public static List<MediaInfo> Read(string file)
        {
            var result = new List<MediaInfo>();

            var xml = XElement.Load(file);
            var mediaCollection = from x in xml.Descendants("Entry")
                                  select new
                                             {
                                                 title = x.Attribute("Title").Value,
                                                 artist = x.Attribute("Artist").Value,
                                                 file = x.Attribute("File").Value
                                             };
            foreach (var m in mediaCollection)
            {
                var mediaInfo = new MediaInfo();
                mediaInfo.Title = m.title;
                mediaInfo.Artist = m.artist;
                mediaInfo.File = m.file;
                result.Add(mediaInfo);
            }

            return result;
        }
    }
}
